package com.intelligent.exception;

import com.intelligent.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.naming.AuthenticationException;
import java.util.stream.Collectors;
import org.springframework.expression.spel.SpelEvaluationException;
import org.springframework.expression.spel.SpelParseException;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<String> handleBusinessException(BusinessException e) {
        return Result.error(e.getMessage());
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handleValidException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getAllErrors().stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.joining(";"));
        return Result.error(message);
    }

    /**
     * 处理HTTP请求方法不支持异常
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result<String> handleMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.warn("[METHOD_NOT_SUPPORTED] {}", e.getMessage());
        String supportedMethods = String.join(", ", e.getSupportedMethods());
        return Result.error("请求方法不支持，当前方法: " + e.getMethod() + "，支持的方法: " + supportedMethods);
    }

    /**
     * 处理运行时异常 -> 直接返回异常消息
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<String> handleRuntimeException(RuntimeException e) {
        log.warn("[RUNTIME] {}", e.getMessage(), e);
        String msg = e.getMessage();
        if (msg == null || msg.isEmpty()) {
            msg = "操作失败";
        }
        return Result.error(msg);
    }

    /**
     * 处理认证/登录异常 -> 返回401
     */
    @ExceptionHandler(AuthenticationException.class)
    public Result<String> handleAuthenticationException(AuthenticationException e) {
        log.warn("[AUTH] Authentication failed: {}", e.getMessage());
        return Result.error(401, "用户名或密码错误");
    }

    /**
     * 处理SpEL表达式解析异常
     */
    @ExceptionHandler({ SpelParseException.class, SpelEvaluationException.class, IllegalStateException.class })
    public Result<String> handleSpelException(Exception e) {
        log.warn("[SPEL] SpEL expression parsing failed: {}", e.getMessage());
        // 对于SpEL解析错误，我们不向用户暴露具体错误信息
        return Result.error("操作日志记录异常，但操作已成功完成");
    }

    /**
     * 处理其他异常
     */
    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e) {
        log.error("[GLOBAL] Unhandled exception", e);
        return Result.error("系统异常，请联系管理员");
    }
}
